<!DOCTYPE html>

<video id="video" width="100%"></video>
<center>
  <button id="record">Record</button>
  <button id="play">Play</button>
</center>

<script src="../jquery.js"></script>
<script src="../../../gun/gun.js"></script>

<script>
var gun = Gun(location.origin + '/gun');
var record = {recorder: null, recording: false};

$('#record').on('click', ()=>{
  if(!record.ing){ return record.stream() }
  $('#record').text("Record");
  if(record.ing.stop){ record.ing.stop() }
  record.ing = false;
})

record.stream = function(){
  navigator.mediaDevices.getDisplayMedia({ video: true }).then(stream => {
    var chunks = []; // we have a stream, we can record it
    record.ing = new MediaRecorder(stream);
    record.ing.ondataavailable = eve => chunks.push(eve.data);
    record.ing.onstop = eve => record.save(new Blob(chunks));
    record.ing.start()
    $('#record').text("End");
  }, err => { console.log(err) });
}

record.save = function(data){
  record.file = record.file || new FileReader();
  record.file.readAsDataURL(data); 
  record.file.onloadend = function(){
    var b64 = record.file.result;
    b64 = "data:video/webm" + b64.slice(b64.indexOf(';'));
    gun.get('test').get('screen').put(b64);
  }
}

$('#play').on('click', ()=>{
  if(record.playing){
    $('#play').text("Play")
    $('#video').get(0).stop();
    record.playing = false;
    return;
  }
  $('#play').text("Stop");
  record.playing = true;
  gun.get('test').get('screen').once((data)=>{
    if(!data){ return }
    $('#video').get(0).src = data;
    $('#video').get(0).play()
  })
})
</script>